<template>
  <!--添加或者修改Spu的结构-->
  <div>
    <el-form ref="form" label-width="80px" :model="spu">
      <!--SPU名称-->
      <el-form-item label="SPU名称">
        <el-input  placeholder="SPU名称" v-model="spu.spuName"></el-input>
      </el-form-item>
      <!--品牌-->
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spu.tmId">
          <el-option :label="tm.tmName" :value="tm.id" v-for="(tm,index) in trademarkList" :key="tm.id"></el-option>
        </el-select>
      </el-form-item>
      <!--SPU描述-->
      <el-form-item label="SPU描述">
        <el-input type="textarea" rows="4" placeholder="描述" v-model="spu.description"></el-input>
      </el-form-item>
      <!--SPU图片-->
      <el-form-item label="SPU图片">
        <!--照片墙 list-type:文件列表类型-->
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :file-list="spuImageList">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <!--销售属性-->
      <el-form-item label="销售属性">
        <el-select :placeholder="`还有${unSelectSaleAttr.length}未选择`" v-model="attrIdAndAttrName">
          <el-option :label="unSelect.name" :value="`${unSelect.id}:${unSelect.name}`" v-for="unSelect in unSelectSaleAttr" :key="unSelect.id"></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-plus" @click="addSaleAttr" :disabled="!attrIdAndAttrName">添加销售属性</el-button>
        <!--表格-->
        <el-table :data="spu.spuSaleAttrList" style="width: 100%" value="" border>
          <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="180"></el-table-column>
          <el-table-column prop="" label="属性名称列表" width="width">
            <template slot-scope="{row,$index}">
              <el-tag
                :key="tag.id"
                v-for="(tag,index) in row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="row.spuSaleAttrValueList.splice(index,1)">
                {{tag.saleAttrValueName}}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="addSaleAttrValue(row)">添加</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="{row,$index}">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="spu.spuSaleAttrList.splice($index,1)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <!--保存与取消-->
      <el-form-item>
        <el-button type="primary" @click="addOrUpdateSpu">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'SpuForm',
  data(){
    return{
      dialogImageUrl: '',
      dialogVisible: false,
      attrIdAndAttrName:'',//收集未选择的属性的id和名字
      //存储SPU数据 设置初始值(添加的时候并没有字段,所以不设置为空对象)
      spu:{
        "category3Id": 0,//三级分类id
        "description": "",//描述
        "tmId": 0,//品牌id
        "spuName": "",//spu名称
        //收集spu图片名称
        "spuImageList": [
          {
            "id": 0,
            "imgName": "",
            "imgUrl": "",
            "spuId": 0
          }
        ],
        // 平台属性与属性值
        "spuSaleAttrList": [
          // {
          //   "baseSaleAttrId": 0,
          //   "id": 0,
          //   "saleAttrName": "",
          //   "spuId": 0,
          //   "spuSaleAttrValueList": [
          //     {
          //       "baseSaleAttrId": 0,
          //       "id": 0,
          //       "isChecked": "",
          //       "saleAttrName": "",
          //       "saleAttrValueName": "",
          //       "spuId": 0
          //     }
          //   ]
          // }
        ],
      },
      trademarkList:[],//品牌数据
      spuImageList:[],//spu图片列表
      saleAttrList:[],//销售属性列表
    }
  },
  computed:{
    unSelectSaleAttr(){
      //计算还有几个属性没有选择
      return this.saleAttrList.filter(item=>{
        return this.spu.spuSaleAttrList.every(item1=>{
          return item.name!==item1.saleAttrName
        })
      })
    }
  },
  methods: {
    //照片墙删除某一图片时触发
    handleRemove(file, fileList) {
      //file:代表删除的那张图 fileList剩余的图片
      this.spuImageList = fileList
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //照片墙上传成功时的回调
    handleSuccess(response,file,fileList){
      this.spuImageList = fileList
    },
    //初始化Spu数据 参数从父组件传过来
    async initSpuData(spu){
      //设置数据 在设计时服务器没有返回spu的数据 在这里设置spu.id = 1 以便后续测试
      spu.id = 1
      try {
        //获取SPU信息
        let spuRes = await this.$API.spu.reqSpu(spu.id)
        if (spuRes.code === 200){
          this.spu = spuRes.data
        }
        //获取品牌信息
        let tadRes = await this.$API.spu.reqTrademarkList()
        if (tadRes.code === 200){
          this.trademarkList = tadRes.data
        }
        //获取Spu图片信息
        let imgRes = await this.$API.spu.reqSpuImageList(spu.id)
        if (imgRes.code === 200){
          let listArr = imgRes.data
          //由于服务器返回的字段是imgName和imgUrl 而组件需要的是name和url
          listArr.forEach((item)=>{
            item.name = item.imgName
            item.url = item.imgUrl
          })
          this.spuImageList = listArr
        }
        //获取整个平台的销售属性
        let saleRes = await this.$API.spu.reqBaseSaleAttrList()
        if (saleRes.code === 200){
          this.saleAttrList = saleRes.data
        }
      }catch (e) {
        alert(e.message)
      }
    },
    //添加新的销售属性
    addSaleAttr(){
      const [baseSaleAttrId,saleAttrName] = this.attrIdAndAttrName.split(':')
      //向spu对象spuSaleAttrList中添加新的销售属性
      let newSaleAttr = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList:[],
      }
      this.spu.spuSaleAttrList.push(newSaleAttr)
      //清空下拉框
      this.attrIdAndAttrName = ''
    },
    //添加新的属性值 添加按钮的回调
    addSaleAttrValue(row){
      //展示input 响应式数据
      this.$set(row,'inputVisible',true)
      //收集属性值 响应式数据
      this.$set(row,'inputValue','')
    },
    //失去焦点时
    handleInputConfirm(row){
      //展示tag
      row.inputVisible = false
      //将属性值加到spuSaleAttrValueList
      let {baseSaleAttrId,inputValue} = row
      inputValue = inputValue.trim()
      if (inputValue.trim()===''){
        this.$message('不能为空')
        return
      }
      if(row.spuSaleAttrValueList.every(item=>item.saleAttrValueName!==inputValue)===false){
        this.$message('不能重复')
        return
      }
      let newSaleAttrValue = {
        saleAttrValueName:inputValue,
          baseSaleAttrId,
      }
      row.spuSaleAttrValueList.push(newSaleAttrValue)
    },
    //保存按钮
    async addOrUpdateSpu(){
      // 整理参数 整合照片墙的数据 加到spu里面
      this.spu.spuImageList = this.spuImageList.map(item=>{
        return{
          imgName:item.name,
          imgUrl:(item.response&&item.response.data)||item.url,//新加入的图的url要是服务器的地址 原图直接在item.url获取
        }
      })
      //保存
      let res = await this.$API.spu.reqUpdateOrAddSpu(this.spu)
      this.$message('测试数据,不能修改 如果是添加,数据已保存\n'+res.message)
      //alert('测试数据,不能修改 如果是添加,数据已保存')
      this.$emit('changeScene', { scene:0,flag:this.spu.id?'修改':'添加' })
      //清除数据
      Object.assign(this._data,this.$options.data())
    },
    //取消按钮
    cancel(){
      //切换场景
      this.$emit('changeScene',{scene:0,flag:'修改'})
      //清除数据 _data:data中的响应式数据
      //this.$options:获取配置对象 其data()执行 返回的响应式数据为空(起始状态)
      Object.assign(this._data,this.$options.data())
    },
    //点击添加SPU按钮时
    async addSpuData(category3Id){
      //获取品牌信息
      let tadRes = await this.$API.spu.reqTrademarkList()
      if (tadRes.code === 200){
        this.trademarkList = tadRes.data
      }
      //获取整个平台的销售属性
      let saleRes = await this.$API.spu.reqBaseSaleAttrList()
      if (saleRes.code === 200){
        this.saleAttrList = saleRes.data
      }
      //收集三级分类ID
      this.spu.category3Id = category3Id
    }
  }
}
</script>

<style>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
